class Admin::CourseWeeksController < ApplicationController

  layout "studio"

  before_action :authorize_course_week

  def index 
    begin_date = Date.current
    begin_week = begin_date.at_beginning_of_week
    course_list = current_company.courses
    
    mon = begin_week
    tue = begin_week + 1.day
    wed = begin_week + 2.day
    thu = begin_week + 3.day
    fri = begin_week + 4.day
    sat = begin_week + 5.day
    sun = begin_week + 6.day

    @monday = course_list.where(day_of_week: mon).order("course_time asc")  
    @tuesday = course_list.where(day_of_week: tue).order("course_time asc")
    @wednesday = course_list.where(day_of_week: wed).order("course_time asc")
    @thursday = course_list.where(day_of_week: thu).order("course_time asc")
    @friday = course_list.where(day_of_week: fri).order("course_time asc")
    @saturday = course_list.where(day_of_week: sat).order("course_time asc")
    @sunday = course_list.where(day_of_week: sun).order("course_time asc")
    respond_to do |format|
      format.html
      format.js
    end
    
  end

  def get_course_week 
    params[:num] ||= 0
    if params[:num].to_i == -1
      begin_date = Date.current - 7.day
    elsif params[:num].to_i == 0
      begin_date = Date.current
    elsif params[:num].to_i == 1
      begin_date = Date.current + 7.day
    end

    begin_week = begin_date.at_beginning_of_week
    course_list = current_company.courses
    
    mon = begin_week
    tue = begin_week + 1.day
    wed = begin_week + 2.day
    thu = begin_week + 3.day
    fri = begin_week + 4.day
    sat = begin_week + 5.day
    sun = begin_week + 6.day

    @monday = course_list.where(day_of_week: mon).order("course_time asc")  
    @tuesday = course_list.where(day_of_week: tue).order("course_time asc")
    @wednesday = course_list.where(day_of_week: wed).order("course_time asc")
    @thursday = course_list.where(day_of_week: thu).order("course_time asc")
    @friday = course_list.where(day_of_week: fri).order("course_time asc")
    @saturday = course_list.where(day_of_week: sat).order("course_time asc")
    @sunday = course_list.where(day_of_week: sun).order("course_time asc")
    
  end

  def show
    @course = Course.find(params[:id])
    @check_ins = CheckIn.where(" course_id = :course_id and student_id is not NULL",course_id: @course.id)
    if @course.course_info.appointmented_or_not
      @appointment_records = AppointmentRecord.where("course_id = :course_id", course_id: @course.id)
    end
  end


  def appointment 
    @course = Course.find(params[:id])
    if @course.appointment_records.map(&:student_id).size > 0
    appointmented_student = Student.where("id in (#{@course.appointment_records.map(&:student_id).uniq.join(",")})")
    @students = current_company.student - appointmented_student 
    else
    @students = current_company.student
    end
    @appointment = AppointmentRecord.new(course_id: @course.id )
  end

  def appointmented
    if params[:appointment_record][:student_id].present?
      
      @course = Course.find_by_id(params[:appointment_record][:course_id]) 
      appointment_record = AppointmentRecord.new(appointment_record_params)
      appointment_record.course_info_id = @course.course_info.id
      appointment_record.appointment_at = Time.now
      appointment_record.operated_by = Employee.find_by(company_id: current_company.id, user_id: current_user.id).id
      if appointment_record.save
        @flag = true
        @message = "预约成功!"
      else
        @flag = false
        @message = "预约失败!"
      end
    else
        @flag = false
        @message = "预约失败 请检查信息是否完整!"
    end
  end

  def student_check
    @course = Course.find(params[:id])
    if @course.course_info.appointmented_or_not
      @students =  @course.appointment_records.map {|ar| ar.student }.uniq
    else
      @students = current_company.student
    end
    @check_in = CheckIn.new(course_id: @course.id)
    @pay_ways = @course.course_info.paying_ways.map(&:pay_type)
    if @course.course_info.sale_or_not
      @pay_ways.push("直接售卖")
    end
  end

  def teacher_check
    @course = Course.find(params[:id])
    @teacher = @course.course_info.teacher
    @check_in = CheckIn.new(course_id: @course.id, teacher_id: @teacher.id)
  end

  def teacher_check_in
    @check_in = CheckIn.new(check_in_params)
    @check_in.checked_at = Time.now
    @check_in.operated_by = Employee.find_by(company_id: current_company.id, user_id: current_user.id).id
    @check_in.save!
  end

  #new private check in
  def new_private_check_in
    @course = Course.find(params[:id])
    @students = @course.appointment_records.map {|ar| ar.student }.uniq
    check_in = CheckIn.new(course_id: @course.id)
  end
  
  #私教课签到
  def private_check_in
    if params[:check_in][:student_id].present?
      @check_in = CheckIn.new(check_in_params)
      @course_info = @check_in.course.course_info
      @check_in.checked_at = Time.now
      @check_in.operated_by = Employee.find_by(company_id: current_company.id, user_id: current_user.id).id
      if @check_in.save!
        @flag = true
      else
        @flag = false
      end
    else
      @flag = false
    end
  end

  def check_in

    Rails.logger.info("ceshi 222222222222!!!")
    if params[:check_in][:student_id].present? && params[:check_in][:pay_way].present?
      Rails.logger.info("ceshi 11111111111!!!")
      @check_in = CheckIn.new(check_in_params)
      @course_info = @check_in.course.course_info
      @check_in.checked_at = Time.now
      @check_in.operated_by = Employee.find_by(company_id: current_company.id, user_id: current_user.id).id
      Rails.logger.info("ceshi !!!")
      if @check_in.save!
        Rails.logger.info("ceshi #############")
        student = @check_in.student
        unless %w{年卡 月卡}.include?(@check_in.pay_way)
          @student_cards = student.student_cards.where(card_type: @check_in.pay_way).where("amount > 0 and invalidated_at > '#{Date.current}'").order(amount: :asc)
          if @check_in.pay_way == "直接售卖"
            #找到买 直接售卖的那个卡
            @student_card = @student_cards.where(course_info_id: @course_info.id).first
            if @student_card.present?
              #学生直接购买了课
              @student_card.amount = 0 
              @student_card.save!
              #若是打包课 这记录还剩多少次
              if @course_info.sale_type == "打包售卖课程"  
                overplus = @course_info.period - 1
                PackSale.create!(course_info_id: @course_info.id, student_id: student.id, amount: overplus) 
              end
              #课程核算 
              reckon_price = @student_card.price
              course_reckon = CourseReckon.create!(studio_id: current_studio.id ,course_id: @check_in.course_id,course_info_id: @course_info.id, student_id: student.id, teacher_id: @course_info.teacher.id, pay_way: @check_in.pay_way, amount: reckon_price)
            end
          elsif @check_in.pay_way == "打包购买"
            @pack_sale = PackSale.where(course_info_id: @course_info.id, student_id: student.id).where("amount > 0").first 
            @pack_sale.amount - 1
            @pack_sale.save!
          else
            #需要消耗的数量
            @student_card = @student_cards.first;
            amount = @course_info.paying_ways.where(pay_type: @check_in.pay_way).first.amount
            if @student_card.card_type == "充值"
            reckon_price = amount
            else
            reckon_price = @student_card.price * amount
            end
            #导师课消
            course_reckon = CourseReckon.create!(studio_id: current_studio.id, course_id: @check_in.course_id,course_info_id: @course_info.id, student_id: student.id, teacher_id: @course_info.teacher.id,pay_way: @check_in.pay_way, amount: reckon_price)
            @student_cards.each do |scard|
              if scard.amount <  amount
                amount = amount - scard.amount
                scard.amount = 0 
                scard.save!
              elsif scard.amount > amount
                scard.amount = scard.amount - amount
                amount = 0
                scard.save!
                break
              end
            end
            #若是打包课 这记录还剩多少次
          #  if @course_info.sale_type == "打包售卖课程"  
          #    overplus = @course_info.period - 1
          #    PackSale.create!(course_info_id: @course_info.id, student_id: student.id, amount: overplus) 
          #  end
          end
          @flag = true
        else
          course_reckon = CourseReckon.create!(studio_id: current_studio.id, course_id: @check_in.course_id, course_info_id: @course_info.id, student_id: student.id, teacher_id: @course_info.teacher.id,pay_way: @check_in.pay_way)
          @flag = true
        end
      end
    else
      @flag = false
    end
  end

  def get_pay_way
    @course_info = CourseInfo.find_by_id(params[:course_info_id])
    @student = Student.find_by_id(params[:student_id])
    if @course_info.sale_type == "打包售卖课程"
      pack_sale = @course_info.pack_sales.where("amount > 0  and  student_id = :student_id", student_id: @student.id).first 
      if pack_sale.present?
        @new_pay_ways = ["打包购买"] 
      else
        pay_ways = @course_info.paying_ways.map(&:pay_type)
        if @course_info.sale_or_not
          pay_ways.push("直接售卖")
        end
        card_type = @student.student_cards.map(&:card_type).uniq
        if card_type.include?("直接售卖")
          unless StudentCard.where(card_type: "直接售卖",course_info_id: @course_info.id).where(" amount > 0 ").first
            card_type - ["直接售卖"]
          end
        end
        @new_pay_ways = pay_ways & card_type
      end
    else
      pay_ways = @course_info.paying_ways.map(&:pay_type)
      if @course_info.sale_or_not
        pay_ways.push("直接售卖")
      end
      card_type = @student.student_cards.map(&:card_type).uniq
      if card_type.include?("直接售卖")
        unless StudentCard.where(card_type: "直接售卖",course_info_id: @course_info.id).where(" amount > 0 ").first.present?
          card_type - ["直接售卖"]
        end
      end
      @new_pay_ways = pay_ways & card_type
    end
  end

  def destroy_appointment_record 
    appointment_record = AppointmentRecord.find_by_id(params[:appointment_record_id])
    @course = appointment_record.course
    appointment_record.destroy

  end

  private

  def check_in_params
    params.require(:check_in).permit(:course_id, :student_id,:teacher_id, :operated_by, :checked_at, :pay_way)
  end

  def appointment_record_params
    params.require(:appointment_record).permit(:course_id, :student_id, :course_info_id, :teacher_id, :operated_by, :appointment_at)
  end


  def authorize_course_week
    authorize CourseInfo , :course_week?
  end

end
